package com.haoqi.document.template.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.deepoove.poi.XWPFTemplate;
import com.haoqi.document.template.dto.in.WordExportWithUrlReqDtoIn;
import com.haoqi.document.template.service.WordExportService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;

@Service
public class WordExportServiceImpl implements WordExportService {

    @Value("${endpoints.prefix}")
    private String prefix;

    @Value("${endpoints.path}")
    private String path;

    @Override
    public String wordDataExport(WordExportWithUrlReqDtoIn dtoIn) throws Exception {
        URL url = new URL(dtoIn.getFileUrl());
        HttpURLConnection httpUrlConnection = (HttpURLConnection)url.openConnection();
        httpUrlConnection.setDoOutput(true);
        httpUrlConnection.setUseCaches(false);
        InputStream inputStream = httpUrlConnection.getInputStream();

        JSONObject obj = JSONObject.parseObject(dtoIn.getData());

        XWPFTemplate template = XWPFTemplate.compile(inputStream).render(obj);

        File tempFile = new File(path + File.separator + System.currentTimeMillis() + "_data.docx");
        OutputStream out = new BufferedOutputStream(new FileOutputStream(tempFile));
        BufferedOutputStream bos = new BufferedOutputStream(out);
        template.write(bos);
        template.close();
        bos.flush();
        bos.close();
        out.flush();
        out.close();

        String fileUrl = prefix + tempFile.getPath();
        return fileUrl;
    }
}